<template>
  <div>
  <!-- 按钮和搜索栏容器 -->
  <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
    <div style="display: flex; gap: 5px;">
      <el-button v-show="addButton"  @click="addOne()">增加会议室</el-button>
      <el-button v-show="returnButton" @click="returnLists()"><el-icon><Back /></el-icon></el-button>
    </div>
    <!-- 搜索栏 -->
    <div>
      <el-input
          v-model="searchname"
          placeholder="请输入会议室名/地址/描述"
          style="width: 250px;"
          @keyup.enter="search()"
      >
        <template #append>
          <el-button @click="search()"><el-icon><Search /></el-icon></el-button>
        </template>
      </el-input>
    </div>
  </div>

  <el-table id="mytable" :data="filteredData" stripe border style="width: 100%">
    <el-table-column fixed prop="id" label="会议室id" width="80" align="center"/>
    <el-table-column prop="name" label="会议室名称" width="150" align="center"/>
    <el-table-column prop="type" label="会议室类型" align="center">
      <template #default="scope">
           {{ scope.row.type==='classroom' ? '教室型' : '圆桌型' }}
      </template>
    </el-table-column>
    <el-table-column prop="capacity" label="容量" align="center"/>
    <el-table-column prop="pricePerHour" label="每小时租赁价格" align="center"/>
    <el-table-column prop="area" label="面积" align="center"/>
    <el-table-column prop="location" label="位置" align="center"/>
    <el-table-column prop="description" label="其他配置项描述" align="center"/>
    <el-table-column prop="hasNatwork" label="网络" align="center">
      <template #default="scope">
           {{ scope.row.hasNetwork ? '有' : '无' }}
      </template>
    </el-table-column>
    <el-table-column prop="hasProjector" label="投影仪" align="center">
      <template #default="scope">
           {{ scope.row.hasProjector ? '有' : '无' }}
      </template>
    </el-table-column>
    <el-table-column prop="hasSpeaker" label="音响" align="center">
      <template #default="scope">
           {{ scope.row.hasSpeaker ? '有' : '无' }}
      </template>
    </el-table-column>
    <el-table-column label="创建时间" align="center">
       <template #default="scope">
          {{ formatCreateTime(scope.row.createTime) }}
       </template>
    </el-table-column>
    <el-table-column label="更新时间" align="center">
       <template #default="scope">
          {{ formatCreateTime(scope.row.updateTime) }}
       </template>
    </el-table-column>
    <el-table-column label="操作" width="180" align="center">
      <template v-slot="scope">
        <el-button link @click="openViewImages(scope.row)" type="primary" size="big">查看图片</el-button>
        <el-button link @click="handleEdit(scope.row)" type="primary" size="big">编辑</el-button>
        <el-button link @click="handleDelete(scope.row)" type="danger" size="big">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <!-- 分页 -->
  <!-- 分页组件 -->
  <el-pagination
    @current-change="handleCurrentChange"
    :current-page="currentPage"
    :page-size="pageSize"
    :total="totalCount"
  >
  </el-pagination>
  <!-- 图片查看对话框 -->
  <el-dialog v-model="imageDialogVisible" title="会议室图片" width="50%">
    <div class="image-viewer">
      <el-carousel height="400px">
        <el-carousel-item v-for="(image, index) in currentImages" :key="index">
          <img :src="image" alt="会议室图片" class="viewer-image">
        </el-carousel-item>
      </el-carousel>
      <div class="image-thumbs" v-if="currentImages.length > 1">
        <div class="thumb-item" v-for="(image, index) in currentImages" :key="index" 
            @click="changeCurrentImage(index)">
          <img :src="image" alt="缩略图" class="thumb-image" :class="{active: currentImageIndex === index}">
        </div>
      </div>
    </div>
    <template #footer>
      <el-button @click="imageDialogVisible = false">关闭</el-button>
    </template>
  </el-dialog>
   <!-- 编辑对话框 -->
  <el-dialog v-model="dialogVisible" title="编辑会议室信息">
    <el-form :model="editForm" label-width="120px">
      <el-form-item label="会议室名称">
        <el-input v-model="editForm.name"/>
      </el-form-item>
      <el-form-item label="会议室类型">
        <el-input v-model="editForm.type"/>
      </el-form-item>
      <el-form-item label="容量">
        <el-input v-model="editForm.capacity"/>
      </el-form-item>
      <el-form-item label="每小时租赁价格">
        <el-input v-model="editForm.pricePerHour"/>
      </el-form-item>
      <el-form-item label="面积">
        <el-input v-model="editForm.area"/>
      </el-form-item>
      <el-form-item label="位置">
        <el-input v-model="editForm.location"/>
      </el-form-item>
      <el-form-item label="网络">
        <el-radio-group v-model="editForm.hasNetwork">
          <el-radio :value="1">有</el-radio>
          <el-radio :value="0">无</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="音响">
         <el-radio-group v-model="editForm.hasSpeaker">
          <el-radio :value="1">有</el-radio>
          <el-radio :value="0">无</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="投影仪">
         <el-radio-group v-model="editForm.hasProjector">
          <el-radio :value="1">有</el-radio>
          <el-radio :value="0">无</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="其他配置项描述">
        <el-input v-model="editForm.description"/>
      </el-form-item>
      <el-form-item label="会议室图片">
          <el-upload
          :show-file-list="true"
          :http-request="handleUpload"
          action="/user/upload/info"
          :on-success="handleAddUploadSuccess"
          :before-upload="beforeAddUpload"
          :file-list="imagePathList"
          list-type="picture-card"
          style="margin-top: 20px;"
          :on-remove="handleFileRemove"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleSave()">保存</el-button>
    </template>
  </el-dialog>

  <!-- 增加用户信息对话框 -->
  <el-dialog v-model="addDialogVisible" title="添加会议室信息">
    <el-form :model="addForm" label-width="120px">
       <el-form-item label="会议室名称">
        <el-input v-model="addForm.name"/>
      </el-form-item>
      <el-form-item label="会议室类型">
        <el-input v-model="addForm.type"/>
      </el-form-item>
      <el-form-item label="容量">
        <el-input v-model="addForm.capcity"/>
      </el-form-item>
      <el-form-item label="每小时租赁价格">
        <el-input v-model="addForm.pricePerHour"/>
      </el-form-item>
      <el-form-item label="面积">
        <el-input v-model="addForm.area"/>
      </el-form-item>
      <el-form-item label="位置">
        <el-input v-model="addForm.location"/>
      </el-form-item>
      <el-form-item label="网络">
       <el-radio-group v-model="addForm.hasNetwork">
          <el-radio value="1">有</el-radio>
          <el-radio value="0">无</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="音响">
        <el-radio-group v-model="addForm.hasSpeaker">
          <el-radio value="1">有</el-radio>
          <el-radio value="0">无</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="投影仪">
        <el-radio-group v-model="addForm.hasProjector">
          <el-radio value="1">有</el-radio>
          <el-radio value="0">无</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="其他配置项描述">
        <el-input v-model="addForm.description"/>
      </el-form-item>
      <el-form-item label="会议室图片">
          <el-upload
          :show-file-list="true"
          :http-request="handleUpload"
          action="/user/upload/info"
          :on-success="handleAddUploadSuccess"
          :before-upload="beforeAddUpload"
          :file-list="imagePathList"
          list-type="picture-card"
          style="margin-top: 20px;"
          :on-remove="handleFileRemove"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="addDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleAdd()">保存</el-button>
    </template>
  </el-dialog>
  </div>
</template>

<script>
import axios from "axios";
import { Search } from '@element-plus/icons-vue';
import { Back,Plus } from "@element-plus/icons-vue";
export default {
  name: "LostAndFoundList",
  data() {
    return {
      listData: [],
      filteredData: [],
      dialogVisible: false,
      addDialogVisible: false,
      editForm: {},
      addForm: {
        images:[],
      },
      editIndex: -1,
      searchname: '',
      returnButton:false,
      addButton:true,
      currentPage:1,
      pageSize:10,
      totalCount:0,
      imagePathList:[],
      imageDialogVisible: false,  
      currentImages: [],          
      currentImageIndex: 0,       
    }
  },
  components :{
     Search,
     Back,
     Plus,
  },
  mounted() {
    this.fetchData();
  },
  methods: {
    handleCurrentChange(page){
        this.currentPage=page;
        if(!this.searchname){
        this.fetchData();
        }else{
          this.search();
        }
    },
    fetchData(){
        axios.get("/admin/room/page",{
          params:{
            pageNum:this.currentPage,
            pageSize:this.pageSize,
          }
        })
        .then(res=>{
          this.listData=res.data.data.records;
          this.totalCount=res.data.data.total;
          if (Array.isArray(this.listData)) {
            this.filteredData = this.listData;
          } else {
              console.error('加载错误');
          }
        }).catch(err=>{
          this.$message.error(err.data.code||"获取列表失败");
        })
    },
    openViewImages(row){
      this.handleViewImages(row);
      this.imageDialogVisible = true;
    },
    // 处理查看图片按钮点击
    handleViewImages(row) {
      // 从行数据中获取图片列表
      axios.get('/admin/room/image/'+row.id).then(res=>{
        if(res.data.code===200){
           this.currentImages = res.data.data;
           console.log(this.currentImages);
           this.currentImageIndex = 0;
        }else {
          this.$message.error(res.data.msg || '图片获取失败！')
        }
      })
      
    },
    
    // 切换当前显示的图片
    changeCurrentImage(index) {
      this.currentImageIndex = index;
    },
    handleDelete(row) {
      this.$confirm('确定删除此会议室吗?', '提示', {
        type: 'warning'
      }).then(() => {
        // 删除当前行数据
        axios.delete("/admin/room/" + row.id)
          .then(response => {
            // 后端返回成功时，提示删除成功
            if (response.data.code === 200) {
              const index = this.listData.findIndex(user => user.id === row.id);
              if (index !== -1) {
                this.listData.splice(index, 1); // 从数据数组中删除该行
              }
              this.filteredData=this.listData;
              this.$message.success('删除成功');
            } else {
              this.$message.error(response.data.msg || '删除失败');
            }
          })
          .catch(error => {
            // 捕获请求错误并显示错误信息
            console.error(error);
            this.$message.error('删除失败');
          });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    async handleEdit(row) {
      this.editIndex = this.listData.findIndex((item) => item.id === row.id);
      this.editForm = { ...row };
     try {
    const res = await axios.get('/admin/room/image/'+row.id);
    if (res.data.code === 200) {
      this.currentImages=res.data.data;
    }else {
      this.$message.error(res.data.msg || '获取失败！')
    }
    } catch (error) {
    this.$message.error(error.message);
    return; // 出错时终止函数
    }
      console.log(this.currentImages);
      let i=0;
      this.imagePathList=this.currentImages.map((item)=>{
        i++;
        return {
        uid:Date.now()+i,
        url:item,
        }
    })
      console.log(row);
      console.log(this.imagePathList);
      this.editForm.images=this.currentImages;
      this.dialogVisible = true;
    },
    handleSave() {
      this.listData[this.editIndex] = { ...this.editForm };
      this.updateToBackend(this.editForm);
      this.dialogVisible = false;
      this.editForm={};
    },
    updateToBackend(row) {
      console.log(row);
      axios.put("/admin/room", row)
          .then((response) => {
            if (response.data.code === 200) {
              this.$message.success('更新成功');
              this.imagePathList=[];
            } else {
              this.$message.error(response.data.msg || '更新失败');
            }
            // 只重新加载用户列表数据
            this.fetchData();
          })
          .catch((error) => {
            console.error(error);
            this.$message.error('更新失败');
            // 只重新加载用户列表数据
            this.fetchData();
          });
    },
    search() {
      this.returnButton=true;
      this.addButton=false;
      axios.get('/admin/room/page',{
          params:{
            keyword:this.searchname,
            pageNum:this.currentPage,
            pageSize:this.pageSize,
          }
        })
      .then(res =>{
        if(res.data.code===200){
          this.filteredData=res.data.data.records;
          this.totalCount=res.data.data.total;
          this.$message.success("查询成功");
        }else {
          this.$message.error(res.data.msg||"查询失败");
        }
      })
    },
    returnLists(){
      this.returnButton=false;
      this.addButton=true;
      this.searchname=null;
      this.currentPage=1;
      this.fetchData();
    },
    goBackToList() {
      this.fetchData();
    },
    addOne() {
      this.imagePathList=[];
      this.addDialogVisible = true;
    },
    handleAdd() {
      console.log('发送的数据:', this.addForm);
      axios.post('/admin/room', this.addForm)
          .then(res => {
            if (res.data.code === 200) {
              this.$message.success('添加成功');
              this.addDialogVisible = false;
              this.addForm={};
              this.fetchData();
            } else {
              //如果失败，提示错误信息
              this.$message.error(res.data.msg||'添加失败');
            }

          }).catch((error) => {
        console.error(error);
        this.$message.error('添加失败');
        // 只重新加载用户列表数据
        this.fetchData();
      });
    },
    formatCreateTime(time){
      return time.replace('T',' ');
    },
    handleAddUploadSuccess(response, file, fileList) {
      this.imagePathList = fileList.map((fileItem) => ({ url: fileItem.url }));
    },
    beforeAddUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isPNG = file.type === 'image/png';
      if (!isJPG && !isPNG) {
        this.$message.error('上传图片只能是 JPG/PNG 格式!');
      }
      return isJPG || isPNG;
    },
    handleUpload(data){
      console.log(data)
            const file = data.file;
            console.log(file)
            const formData = new FormData();
            formData.append('files', file);
 
            axios.post('/common/meeting-room', formData, {
                headers: {
                    'Content-Type': 'multipart/form-data'
                }
            }).then(res => {
                console.log(res)
                if (res.data.code === 200) {
                    this.$message.success("图片上传成功！");
                    this.imagePathList.push({
                      uid:file.uid,
                      url:res.data.data[0]
                  })
                  
                  if(JSON.stringify(this.editForm)!=='{}'){
                    console.log(JSON.stringify(this.editForm));
                    this.editForm.images.push(res.data.data[0])
                  }else {
                    console.log(JSON.stringify(this.addForm));
                    this.addForm.images.push(res.data.data[0]);
                  }
                    
                } else {
                    this.$message.error("图片上传失败！！");
                }
                // this.$refs.upload.clearFiles(); // 清除上传的文件列表
            })
    },
    handleFileRemove(file, fileList) {
      // 从 imagePathList 中移除文件
      const index = this.imagePathList.findIndex(item => item.uid === file.uid);
      if (index!== -1) {
        this.imagePathList.splice(index, 1);
        console.log(index);
        if(JSON.stringify(this.editForm)!=='{}'){
          this.editForm.images.splice(index,1);
        }else {
          this.addForm.images.splice(index,1);
        }
      }
      console.log(fileList)
    }
  },
}

</script>

<style scoped>
.clicked-s {
  background-color: green;
  color: white;
}
.image-viewer {
  text-align: center;
}
.viewer-image {
  max-width: 100%;
  max-height: 400px;
  cursor: zoom-in;
}
.image-thumbs {
  display: flex;
  justify-content: center;
  gap: 10px;
  margin-top: 10px;
  overflow-x: auto;
  padding: 5px 0;
}
.thumb-item {
  width: 80px;
  height: 80px;
  cursor: pointer;
  border: 2px solid transparent;
  transition: all 0.3s;
}
.thumb-item:hover {
  border-color: #409EFF;
}
.thumb-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.active {
  border-color: #409EFF !important;
}
</style>